﻿
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Serialization;

// 订单明细类
//[Serializable]
public class OrderDetails
{
    public string ProductName { get; set; }
    public double Price { get; set; }
    public int Quantity { get; set; }

    // 无参构造函数（XML序列化需要）
    public OrderDetails() { }

    public OrderDetails(string productName, double price, int quantity)
    {
        ProductName = productName;
        Price = price;
        Quantity = quantity;
    }

    public override bool Equals(object obj)
    {
        return obj is OrderDetails details &&
               ProductName == details.ProductName &&
               Price == details.Price &&
               Quantity == details.Quantity;
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(ProductName, Price, Quantity);
    }

    public override string ToString()
    {
        return $"商品名称: {ProductName}, 单价: {Price}, 数量: {Quantity}";
    }
}

// 订单类
//[Serializable]
public class Order
{
    public string OrderId { get; set; }
    public string Customer { get; set; }
    public List<OrderDetails> OrderDetails { get; set; }

    [XmlIgnore] // 忽略计算属性的序列化
    public double TotalAmount
    {
        get { return OrderDetails?.Sum(d => d.Price * d.Quantity) ?? 0; }
    }

    // 无参构造函数（XML序列化需要）
    public Order()
    {
        OrderDetails = new List<OrderDetails>(); // 初始化列表避免空引用
    }

    public Order(string orderId, string customer, List<OrderDetails> orderDetails)
    {
        OrderId = orderId;
        Customer = customer;
        OrderDetails = orderDetails;
    }

    public override bool Equals(object obj)
    {
        return obj is Order order &&
               OrderId == order.OrderId &&
               Customer == order.Customer &&
               OrderDetails.SequenceEqual(order.OrderDetails);
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(OrderId, Customer, OrderDetails);
    }

    public override string ToString()
    {
        string details = string.Join("\n  ", OrderDetails.Select(d => d.ToString()));
        return $"订单号: {OrderId}, 客户: {Customer}, 总金额: {TotalAmount}\n  {details}";
    }
}

// 订单服务类
public class OrderService
{
    private List<Order> orders = new List<Order>();

    // 导出订单到XML文件
    public void Export(string filePath)
    {
        try
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<Order>));
            using (FileStream fs = new FileStream(filePath, FileMode.Create))
            {
                serializer.Serialize(fs, orders);
            }
            Console.WriteLine($"成功导出订单数据到: {filePath}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"导出失败: {ex.Message}");
        }
    }

    // 从XML文件导入订单
    // Import 方法
    public void Import(string filePath)
    {
        if (!File.Exists(filePath))
            throw new FileNotFoundException("文件未找到", filePath);

        XmlSerializer serializer = new XmlSerializer(typeof(List<Order>));
        using (FileStream fs = new FileStream(filePath, FileMode.Open))
        {
            List<Order> importedOrders = (List<Order>)serializer.Deserialize(fs);
            orders = importedOrders;
        }
        Console.WriteLine($"成功从 {filePath} 导入订单数据");
    }

    // AddOrder 方法
    public void AddOrder(Order order)
    {
        if (orders.Any(o => o.OrderId == order.OrderId))
        {
            throw new Exception($"订单号 {order.OrderId} 已存在，无法添加。");
        }
        orders.Add(order);
    }

    public void DeleteOrder(string orderId)
    {
        var order = orders.FirstOrDefault(o => o.OrderId == orderId);
        if (order == null)
        {
            throw new Exception($"未找到订单号为 {orderId} 的订单，删除失败。");
        }
        orders.Remove(order);
    }

    public void ModifyOrder(Order newOrder)
    {
        var index = orders.FindIndex(o => o.OrderId == newOrder.OrderId);
        if (index == -1)
        {
            throw new Exception($"未找到订单号为 {newOrder.OrderId} 的订单，修改失败。");
        }
        orders[index] = newOrder;
    }

    public List<Order> QueryOrdersByOrderId(string orderId)
    {
        return orders.Where(o => o.OrderId == orderId).OrderBy(o => o.TotalAmount).ToList();
    }

    public List<Order> QueryOrdersByProductName(string productName)
    {
        return orders.Where(o => o.OrderDetails.Any(d => d.ProductName == productName))
                     .OrderBy(o => o.TotalAmount).ToList();
    }

    public List<Order> QueryOrdersByCustomer(string customer)
    {
        return orders.Where(o => o.Customer == customer).OrderBy(o => o.TotalAmount).ToList();
    }

    public List<Order> QueryOrdersByTotalAmount(double amount)
    {
        return orders.Where(o => o.TotalAmount == amount).OrderBy(o => o.TotalAmount).ToList();
    }

    public void SortOrders()
    {
        orders = orders.OrderBy(o => o.OrderId).ToList();
    }

    public void SortOrders(Func<Order, object> sortExpression)
    {
        orders = orders.OrderBy(sortExpression).ToList();
    }

    public List<Order> GetAllOrders()
    {
        return orders;
    }
}

class Program
{
    static void Main()
    {
        OrderService service = new OrderService();

        // 添加测试订单
        try
        {
            var orderDetails1 = new List<OrderDetails>
            {
                new OrderDetails("商品A", 10, 2),
                new OrderDetails("商品B", 20, 1)
            };
            var order1 = new Order("001", "客户甲", orderDetails1);
            service.AddOrder(order1);

            var orderDetails2 = new List<OrderDetails>
            {
                new OrderDetails("商品C", 30, 1)
            };
            var order2 = new Order("002", "客户乙", orderDetails2);
            service.AddOrder(order2);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

        // 导出订单
        string xmlPath = @"orders.xml";
        service.Export(xmlPath);

        // 清空当前订单（模拟重新加载）
        Console.WriteLine("\n清空当前订单...");
        service = new OrderService();
        Console.WriteLine($"当前订单数量: {service.GetAllOrders().Count}");

        // 导入订单
        service.Import(xmlPath);

        // 打印导入的订单
        Console.WriteLine("\n导入后的订单列表:");
        foreach (var order in service.GetAllOrders())
        {
            Console.WriteLine(order);
            Console.WriteLine("-------------------");
        }
    }
}